<template>
  <div v-loading="loading">
    <!-- 头部 -->
    <el-card class="head-content">
      <span v-for="(item,index) of crumbs" :key="index" @click="crumbsChange(item)">
        <i v-show="index != 0" class="el-icon-arrow-right head-content-txt" />
        <span class="head-content-txt">{{ item }}</span>
      </span>
    </el-card>
    <!-- 主体 -->
    <el-card class="form-content">
      <el-form ref="form" :model="form" size="small" label-width="120px" :rules="rules" :validate-on-rule-change="false">
        <el-form-item label="类型选择" prop="type">
          <el-radio-group v-model="form.type" :disabled="articleDisabled" @change="tabChange">
            <el-radio label="M">图文</el-radio>
            <el-radio label="P">图片</el-radio>
            <el-radio label="R">视频</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="标题" prop="articleTitle">
          <el-input v-model="form.articleTitle" :disabled="articleDisabled" placeholder="请输入标题" class="baseItem" maxlength="30" show-word-limit type="text" />
        </el-form-item>
        <el-form-item label="分类" prop="categoryList">
          <el-cascader
            v-model="form.categoryList"
            class="baseItem"
            :disabled="articleDisabled"
            placeholder="请选择分类"
            :props="cascaderProps"
            :options="categoryListData"
          />
          <el-button v-show="!categoryListData.length" type="text" class="mg-l-20" @click="toAdd('category')">去添加</el-button>
        </el-form-item>
        <el-form-item label="作者" prop="authorName">
          <el-select v-model="form.authorName" placeholder="请选择作者" class="baseItem" :disabled="articleDisabled">
            <el-option
              v-for="author of authorList"
              :key="author.id"
              :disabled="articleDisabled"
              :label="author.authorName"
              :value="author.authorName"
            />
          </el-select>
          <el-button v-show="!authorList.length" type="text" class="mg-l-20" @click="toAdd('author')">去添加</el-button>
        </el-form-item>
        <el-form-item label="标签" prop="labelList">
          <span class="tipText">最多可选择五个</span>
          <el-button v-show="!labelDataList.length" type="text" class="mg-l-20" @click="toAdd('label')">去添加</el-button>
          <el-checkbox-group v-model="form.labelList" :disabled="articleDisabled" :max="5">
            <el-checkbox
              v-for="label of labelDataList"
              :key="label.labelId"
              :label="label.labelId"
            >{{ label.labelNm }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <!-- 图文 -->
        <template v-if="form.type === 'M'">
          <el-form-item label="文章详情" prop="content">
            <TiEditor ref="Ti" v-model="form.content" width="700" :readonly="articleDisabled" />
          </el-form-item>
        </template>
        <!-- 图片 -->
        <template v-else-if="form.type === 'P'">
          <el-form-item label="文章详情" prop="content">
            <div class="tipText">图片要求:宽度1620px，大小1M内。已上传{{ fileList.length }}/10张</div>
            <el-upload
              v-show="fileList.length < 10"
              class="app-uploader-img-plus"
              :disabled="articleDisabled"
              :action="actionUrl"
              :data="dataObj"
              :show-file-list="false"
              :on-remove="beforeRemove"
              :headers="uploadHeaders"
              :on-success="(...arg) => handleAvatarSuccess('fileList',...arg)"
              :before-upload="(...arg) => beforeAvatarUpload('img',...arg)"
            >
              <i class="el-icon-plus app-uploader-img-plus-icon" />
            </el-upload>
            <div class="fileList">
              <div v-for="(file, idx) of fileList" :key="file" class="fileItem">
                <div v-show="!articleDisabled" class="clsoe">
                  <i class="el-icon-delete" @click="removeFile(fileList,idx)" />
                </div>
                <el-image
                  class="avatar"
                  style="width: 100px; height: 100px"
                  :src="file"
                  fit="contain"
                />
              </div>
            </div>
          </el-form-item>
        </template>
        <!-- 视频 -->
        <template v-else-if="form.type === 'R'">
          <el-form-item label="文章详情" prop="content">
            <div class="tipText">视频要求：大小200M内</div>
            <el-upload
              v-show="fileList.length == 0"
              class="app-uploader-img-plus"
              :disabled="articleDisabled"
              :action="actionUrl"
              :data="dataObj"
              :show-file-list="false"
              :on-remove="beforeRemove"
              :headers="uploadHeaders"
              :on-success="(...arg) => handleAvatarSuccess('video',...arg)"
              :before-upload="(...arg) => beforeAvatarUpload('video',...arg)"
            >
              <i class="el-icon-plus app-uploader-img-plus-icon" />
            </el-upload>
            <div class="fileList">
              <div v-for="(file, idx) of fileList" :key="file" class="fileItem">
                <div v-show="!articleDisabled" class="clsoe">
                  <i class="el-icon-delete" @click="removeFile(fileList,idx)" />
                </div>
                <video :src="file" controls style="width:100%; max-height: 500px" />
              </div>
            </div>
          </el-form-item>
        </template>
        <el-form-item label="封面" prop="coverPath">
          <div class="tipText">图片要求：尺寸330*220，大小1M内。</div>
          <el-upload
            class="fl app-uploader-img-plus"
            :disabled="articleDisabled"
            :action="actionUrl"
            :data="dataObj"
            :show-file-list="false"
            :headers="uploadHeaders"
            :on-success="(...arg) => handleAvatarSuccess('coverPath',...arg)"
            :before-upload="(...arg) => beforeAvatarUpload('img',...arg)"
          >
            <el-image
              v-if="form.coverPath"
              class="avatar"
              style="width: 100px; height: 100px"
              :src="form.coverPath"
              fit="contain"
            />
            <i v-else class="el-icon-plus app-uploader-img-plus-icon" />
          </el-upload>
        </el-form-item>
        <el-form-item label="分享副标题" prop="secondTitle">
          <el-input
            v-model="form.secondTitle"
            :disabled="articleDisabled"
            class="baseItem"
            maxlength="30"
            show-word-limit
            type="textarea"
          />
        </el-form-item>
        <!-- 可看范围 -->
        <SelectRole v-model="agtRadio" :form="form" :disabled="articleDisabled" />
        <!-- 按钮组 -->
        <el-form-item>
          <div v-if="['add','edit'].includes(pageType)">
            <el-button @click="preview">预览</el-button>
            <el-button @click="save('W')">保存至草稿</el-button>
            <el-button type="primary" @click="putaway">立即上架</el-button>
          </div>
          <div v-if="pageType == 'detail'">
            <el-button @click="back">返回</el-button>
          </div>
        </el-form-item>
      </el-form>
      <el-dialog title="预览" :visible.sync="dialogFormVisible" width="90%">
        <PreviewArticle
          v-if="dialogFormVisible"
          :form="form"
          :file-list="fileList"
          :label-obj="labelObj"
        />
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
// 引入富文本组件
import TiEditor from '@/components/Tinymce'
import PreviewArticle from './components/PreviewArticl.vue'
import SelectRole from './components/SelectRole.vue'
import { v4 as uuidv4 } from 'uuid'
import {
  categoryInfoList,
  authorInfoList,
  articleInfoAdd,
  articleInfoDetail,
  doGetOssSign,
  articleInfoUpd,
  labelInfoAllList } from '@/api/knowledge'
import { imgUploadUrl } from '@/api/upload'
import { getToken } from '@/utils/auth'
export default {
  components: {
    TiEditor, PreviewArticle, SelectRole
  },
  data() {
    return {
      loading: false,
      titleObj: {
        add: '新增',
        edit: '编辑',
        detail: '查看'
      },
      uploadHeaders: {
        'X-KDADMIN-TOKEN': getToken()
      },
      dataObj: {
        policy: '',
        signature: '',
        key: '',
        ossaccessKeyId: '',
        success_action_status: '',
        dir: '',
        host: ''
      },
      actionUrl: imgUploadUrl,
      cascaderProps: {
        label: 'categoryName',
        value: 'id'
      },
      dialogFormVisible: false, // 预览模态框
      categoryListData: [],
      categoryObj: {},
      authorList: [],
      labelDataList: [],
      labelObj: {},
      agtRadio: 1,
      fileList: [],
      baseDetail: {},
      form: {
        articleTitle: '', // 标题
        secondTitle: '', // 副标题
        type: 'M', // 类型选择
        authorName: '', // 作者
        status: '', // 状态
        coverPath: '', // 上传的照片
        agtList: [], // agtList租户id：全部传0
        labelList: [], // labelList标签集合
        roleNm: [], // 指定范围
        content: '', // 内容
        categoryList: '' // 分类
      }
    }
  },
  computed: {
    crumbs() {
      const { backPage, type } = this.$route.query
      const arr = ['文章管理', this.titleObj[type]]
      if (backPage == 'Draft') {
        arr.splice(1, 0, '草稿')
      }
      return arr
    },
    rules() {
      const { type } = this.form
      const baseObj = {
        articleTitle: [{ required: true, message: '请输入标题', trigger: ['blur', 'change'] }],
        categoryList: [{ required: true, message: '请输入分类', trigger: ['blur', 'change'] }],
        labelList: [{ required: true, trigger: ['blur', 'change'], validator: this.validFun }],
        authorName: [{ required: true, message: '请输入作者', trigger: ['blur', 'change'] }],
        agtList: [{ validator: this.validRule, required: true, trigger: ['blur', 'change'] }],
        roleNm: [{ validator: this.validRule, required: true, trigger: ['blur', 'change'] }],
        secondTitle: [{ required: true, message: '请输入分享副标题', trigger: ['blur', 'change'] }],
        coverPath: [{ required: true, message: '请上传封面', trigger: ['blur', 'change'] }],
        content: [{ required: true, trigger: ['blur', 'change'], validator: this.validFun }]
      }
      const dynObj = {}
      // if (type == 'M') {
      //   dynObj = {

      //   }
      // }

      return {
        ...baseObj,
        ...dynObj
      }
    },
    pageType() {
      return this.$route.query.type || 'add'
    },
    articleDisabled() {
      const { type } = this.$route.query
      return type == 'detail'
    }
  },
  created() {
  },
  async mounted() {
    console.log(1)
    await this.getBasedata()
    console.log(3)
    const { articleId } = this.$route.query
    if (['detail', 'edit'].includes(this.pageType)) {
      articleInfoDetail({ id: articleId }).then(res => {
        const detail = res.data
        const categoryList = detail.categoryList ? JSON.parse(detail.categoryList) : []
        const agtList = detail.agtList != '0' ? JSON.parse(detail.agtList) : []

        let labelList = detail.labelList ? JSON.parse(detail.labelList) : []
        // 过滤被禁用的标签
        labelList = labelList.filter(item => {
          return this.labelDataList.some(v => v.labelId == item.labelId)
        })
        console.log('labelList', labelList)
        const obj = {
          ...res.data,
          categoryList: categoryList.map(item => item.categoryId),
          oldCategoryList: JSON.parse(detail.categoryList),
          labelList: labelList.filter(v => v.labelId).map(item => item.labelId),
          oldLabelList: JSON.parse(detail.labelList),
          roleNm: detail.roleNm ? detail.roleNm.split(',') : [],
          agtList: agtList.map(item => item.agtId).filter(v => !!v)
        }
        if (['P', 'R'].includes(obj.type)) {
          this.fileList = obj.content.split(',')
          obj['content'] = ''
        }
        this.form = obj
        this.baseDetail = JSON.parse(JSON.stringify(obj))
        if (agtList.length) {
          this.agtRadio = 2
        } else {
          this.agtRadio = 1
        }
        console.log('详情 === ', res, this.form, agtList)
      })
    }
  },
  methods: {
    crumbsChange(key) {
      console.log(key)
      if (key == '文章管理') {
        this.back()
      }
    },
    validFun(rule, value, callback) {
      console.log('rule, value, callback', rule, value)
      const { field } = rule
      const { type, content } = this.form
      let text = ''
      switch (field) {
        case 'content':
          if (type == 'M') {
            text = content ? '' : '文章详情必填'
          } else {
            text = this.fileList.length ? '' : '文章详情必填'
          }
          break
        case 'labelList': {
          const labelList = this.form.labelList.map(id => {
            const obj = this.labelObj[id] || {}
            return {
              'labelId': obj.labelId,
              'labelNm': obj.labelNm
            }
          }).filter(v => v.labelId)
          text = labelList.length ? '' : '请选择标签'
        }
          break
      }
      text ? callback(text) : callback()
    },
    toAdd(type) {
      // 基础数据没有时  去添加
      switch (type) {
        case 'category':
          this.$router.push({
            path: '/knowledge/ArticleClassManagement',
            query: { pageType: 'noDataAdd' }
          })
          break
        case 'author':
          this.$router.push({
            path: '/knowledge/AuthorManagement',
            query: { pageType: 'noDataAdd' }
          })
          break
        case 'label':
          this.$router.push({
            path: '/knowledge/LabelManagement',
            query: { pageType: 'noDataAdd' }
          })
          break
      }
    },
    preview() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.dialogFormVisible = true
        }
      })
    },
    back() {
      const { backPage } = this.$route.query
      this.$router.push({ name: backPage || 'Article' })
      // this.$router.go(-1)
    },
    // 类型切换
    tabChange(val) {
      console.log('tabChange == ', val)
      this.form.content = ''
      this.fileList = []
    },
    removeFile(arr, index) {
      arr.splice(index, 1)
    },
    validRule(rule, value, callback) {
      const { field } = rule
      console.log('validRule', this.form)
      if (field == 'agtList') {
        if (this.agtRadio == 2 && !this.form.agtList.length) {
          callback('请选择机构')
        } else {
          callback()
        }
      } else if (field == 'roleNm') {
        if (this.agtRadio == 2 && (!this.form.roleNm || !this.form.roleNm.length)) {
          callback('至少选择一个范围')
        } else {
          callback()
        }
      } else if (field == 'coverPath') {
        if (!this.form.coverPath) {
          callback('请上传封面')
        } else {
          callback()
        }
      } else {
        callback()
      }
    },
    // 上架操作 需要二次验证
    putaway() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.$confirm('是否确定上架当前文章', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            // if (this.form.id) {
            //   articleInfoPut({
            //     id: this.form.id,
            //     status: 'Y'
            //   }).then(res => {
            //     this.$message.success('操作成功')
            //     this.back()
            //   })
            // } else {
            this.save('Y')
            // }
          })
        }
      })
    },
    save(status) {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.form.categoryList.length < 3) {
            this.$message.error('文章分类必须选择三级分类')
            return
          }

          const { type } = this.form
          const labelList = this.form.labelList.map(id => {
            const obj = this.labelObj[id] || {}
            return {
              'labelId': obj.labelId,
              'labelNm': obj.labelNm
            }
          }).filter(v => v.labelId)
          const categoryList = this.form.categoryList.map(id => {
            const obj = this.categoryObj[id] || {}
            return {
              'status': obj.status,
              'categoryId': obj.id,
              'categoryLevel': obj.level,
              'categoryNm': obj.categoryName
            }
          })
          // SelectRole组件中，根据agtList动态重组agtListObj数据
          const agtList = this.agtRadio == 1 ? [] : this.form.agtListObj
          const lastCategory = categoryList[categoryList.length - 1]
          if (lastCategory.status == 'N') {
            this.$message.error('该分类已被禁用，请重新选择！')
            return
          }

          const obj = {
            ...this.form,
            labelList,
            categoryList,
            agtList,
            status,
            roleNm: this.form.roleNm.join(',')
          }
          // 图片和视频类型 降content转为字符串
          if (['R', 'P'].includes(type)) {
            obj['content'] = this.fileList.join(',')
          }
          console.log('obj', obj, this.form)
          if (this.form.id) {
            // 修改
            articleInfoUpd({
              ...obj,
              oldAuthorName: this.baseDetail.authorName,
              id: this.form.id
            }).then(res => {
              console.log('res', res)
              this.$message.success('操作成功')
              this.back()
            })
          } else {
            // 新增
            articleInfoAdd(obj).then(res => {
              console.log('res', res)
              this.$message.success('操作成功')
              this.back()
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    handleAvatarSuccess(type, res, file) {
      console.log('handleAvatarSuccess', type, res)
      this.loading = false
      // if (res.code === 0) {
      if (type == 'coverPath') {
        this.form.coverPath = this.dataObj.host + this.dataObj.key
        this.$refs['form'].validateField('coverPath')
      } else {
        this.fileList.push(this.dataObj.host + this.dataObj.key)
        this.$refs['form'].validateField('content')
      }
      // } else {
      //   this.$message.error(res.msg)
      // }
    },
    // 上传前处理
    async beforeAvatarUpload(type, file) {
      this.loading = true
      let result = ''
      result = await this.$beforeUploadFile(file, this, {
        fileSizes: type == 'img' ? 1 : 200,
        fileType: type
      })
      console.log('beforeAvatarUpload', result)
      if (result) {
        this.loading = true
        return doGetOssSign().then(response => {
          this.actionUrl = response.data.host
          this.dataObj.policy = response.data.policy
          this.dataObj.signature = response.data.signature
          this.dataObj.ossaccessKeyId = response.data.accessid
          this.dataObj.key = response.data.dir + uuidv4() + `_${file.name}`
          this.dataObj.dir = response.data.dir
          this.dataObj.host = response.data.host
          this.dataObj.success_action_status = '200'
          console.log('doGetOssSign', this.dataObj)
          return true
        })
      } else {
        this.loading = result
        return Promise.reject()
      }
    },
    getBasedata() {
      return Promise.all([
        categoryInfoList().then(res => {
          console.log('res', res)
          this.categoryListData = this.resetData(res.data)
        }),
        authorInfoList({
          status: 'Y',
          pageSize: 999,
          currentPage: 1
        }).then(res => {
          this.authorList = res.data.list
        }),
        labelInfoAllList({ status: 'Y' }).then(res => {
          this.labelDataList = res.data.map(label => {
            this.$set(this.labelObj, label.labelId, label)
            return { ...label, id: label.labelId }
          })
          console.log('labelObj', this.labelObj)
        })
      ])
    },
    resetData(arr) {
      return arr.map(item => {
        this.$set(this.categoryObj, item.id, item)
        return {
          ...item,
          children: item.children.length ? this.resetData(item.children) : null
        }
      })
    },
    beforeRemove(file, fileList) {
      console.log('beforeRemove', file)
      this.loading = false
    }
  }
}
</script>

<style lang="scss" scoped>
.tipText{
  color: #b0acac;
  font-size: 12px;
}
.app-uploader-img-plus {
    width: 100px;
    height: 100px;
    border: 1px dotted #ddd;
    .avatar{
      width: 100px;
      height: 100px;
    }
    .app-uploader-img-plus-icon {
      font-size: 28px;
      color: #8c939d;
      width: 100px;
      height: 100px;
      line-height: 100px;
      text-align: center;
    }
  }
  .baseItem{
    width: 400px;
  }
  .head-content {
    width: 100%;

    .head-content-txt {
      font-size: 24px;
      font-weight: 550;
    }
  }

  .form-content {
    margin-top: 10px;
    .fileList{
      display: flex;
      .fileItem{
        display: inline-block;
        position: relative;
        margin-right: 10px;
        margin-bottom: 10px;
        video{
          max-width: 500px;
          max-height: 500px;
        }
        .clsoe{
          position: absolute;
          z-index: 10;
          top: 0;
          right: 0;
          left: 0;
          bottom: 0;
          background: rgba($color: #000000, $alpha: 0.5);
          display: none;
          justify-content: center;
          align-items: center;
          i{
            color: #fff;
            font-size: 20px;
            cursor: pointer;
          }
        }
        &:hover{
          .clsoe{
            display: flex;
          }
        }
      }
    }

}

</style>
